import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { AxiosRequestConfig } from 'axios';

@Injectable()
export class CommonRequestService {
  constructor(private readonly httpService: HttpService) {}

  request(config?: AxiosRequestConfig): Promise<any> {
    return this.httpService.request(config).toPromise().then((res) => {
      if (res.status === 200 && res.data) {
        return Promise.resolve(res.data)
      }
      return Promise.reject()
    });
  }
  get(url: string, config?: AxiosRequestConfig): Promise<any> {
    return this.httpService.get(url, config).toPromise().then((res) => {
      if (res.status === 200 && res.data) {
        return Promise.resolve(res.data)
      }
      return Promise.reject()
    });
  }
  post(url: string, data?: any, config?: AxiosRequestConfig): Promise<any> {
    return this.httpService.post(url, data, config).toPromise().then((res) => {
      if (res.status === 200 && res.data) {
        return Promise.resolve(res.data)
      }
      return Promise.reject()
    });
  }
  postStream(url: string, data?: any, config?: AxiosRequestConfig): Promise<any> {
    return this.httpService.post(url, data, config).toPromise().then((res) => {
      return Promise.resolve(res)
    });
  }
  put(url: string, data?: any, config?: AxiosRequestConfig): Promise<any> {
    return this.httpService.put(url, data, config).toPromise().then((res) => {
      if (res.status === 200 && res.data) {
        return Promise.resolve(res.data)
      }
      return Promise.reject()
    });
  }
  delete(url: string, config?: AxiosRequestConfig): Promise<any> {
    return this.httpService.delete(url, config).toPromise().then((res) => {
      if (res.status === 200 && res.data) {
        return Promise.resolve(res.data)
      }
      return Promise.reject()
    });
  }
}
